package org.grapes.wine.api.server.startup;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.grapes.wine.api.server.database.DerbyConfig;

public class TomcatStartupListener implements ServletContextListener {

	public void contextInitialized(ServletContextEvent sce) {
		ServletContext servletContext = sce.getServletContext();
		
		InputStream in = servletContext.getResourceAsStream("/WEB-INF/derby.properties");
		Properties properties = new Properties();
		try {
			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.setProperty("derby.system.home",
				properties.getProperty("derby.system.home"));
		DerbyConfig.user = properties.getProperty("derby-user");
		DerbyConfig.password = properties.getProperty("derby-password");
		try {
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		// initialize Hibernate Session Factory
		String path = servletContext.getRealPath("Web-INF/hibernate.cfg.xml");
		InitSessionFactory.setConfigFileLocation(path);
		InitSessionFactory.getInstance();
	}
	
	public void contextDestroyed(ServletContextEvent arg0) {
		InitSessionFactory.close();
	}
}
